<template>
  <fy-table-mobile
    v-if="$q.screen.lt.sm"
    :table-data="tableData"
    :columns="computedColumns"
    :title="title"
    :row-key="rowKey"
    :selection="selection"
    :selected="selectedValue"
    :loading="loading"
    @update:selected="handleSelection"
  >
    <!--    <template v-for="(_, name) in $slots" #[name]="slotData">-->
    <!--      <slot :name="name" v-bind="slotData || {}" />-->
    <!--    </template>-->
  </fy-table-mobile>

  <fy-table-desktop
    v-else
    :table-data="tableData"
    :columns="computedColumns"
    :title="title"
    :row-key="rowKey"
    :selection="selection"
    :selected="selectedValue"
    :loading="loading"
    @update:selected="handleSelection"
  >
    <template v-for="(_, name) in $slots" #[name]="slotData">
      <slot :name="name" v-bind="slotData || {}" />
    </template>
  </fy-table-desktop>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useQuasar } from 'quasar'
import FyTableDesktop from './components/Desktop.vue'
import FyTableMobile from './components/Mobile.vue'

const $q = useQuasar()

const props = defineProps({
  tableData: {
    type: Array,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
  },
  title: {
    type: String,
    default: '',
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  selection: {
    type: String,
    default: '',
  },
  selected: {
    type: [Array, Object],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:selected', 'selection'])

// 处理列配置
const computedColumns = computed(() => {
  const cols = props.columns.map((col) => ({
    ...col,
    field: col.field || col.name,
  }))
  return cols
})

const selectedValue = ref(props.selected)

watch(
  () => props.selected,
  (newVal) => {
    selectedValue.value = Array.isArray(newVal) ? [...newVal] : newVal
  },
  { deep: true },
)

const handleSelection = (val) => {
  selectedValue.value = val
  emit('update:selected', val)
  emit('selection', val)
}
</script>
